package com.runmi.webchat.aftersale.web.api.controller;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.runmi.webchat.aftersale.common.mail.SendMessage;
import com.runmi.webchat.aftersale.common.mail.SetupMail;
import com.runmi.webchat.aftersale.common.page.PageModel;
import com.runmi.webchat.aftersale.common.result.Result;
import com.runmi.webchat.aftersale.common.result.ResultFactory;
import com.runmi.webchat.aftersale.common.utils.DateUtil;
import com.runmi.webchat.aftersale.common.utils.StringUtil;
import com.runmi.webchat.aftersale.dbcore.dao.SetupItemDao;
import com.runmi.webchat.aftersale.dbcore.dao.SetupOrderDao;
import com.runmi.webchat.aftersale.dbcore.dao.SetupOrderDetailDao;
import com.runmi.webchat.aftersale.dbcore.dao.UserOpenIdDao;
import com.runmi.webchat.aftersale.dbcore.entity.RegionInfo;
import com.runmi.webchat.aftersale.dbcore.entity.SetupItem;
import com.runmi.webchat.aftersale.dbcore.entity.SetupOrder;
import com.runmi.webchat.aftersale.dbcore.entity.SetupOrderDetail;
import com.runmi.webchat.aftersale.dbcore.entity.ShopInfo;
import com.runmi.webchat.aftersale.dbcore.entity.UserOpenId;
import com.runmi.webchat.aftersale.dbcore.mapper.RegionInfoMapper;
import com.runmi.webchat.aftersale.dbcore.mapper.SetupItemMapper;
import com.runmi.webchat.aftersale.dbcore.mapper.SetupOrderDetailMapper;
import com.runmi.webchat.aftersale.dbcore.mapper.SetupOrderMapper;
import com.runmi.webchat.aftersale.dbcore.mapper.ShopInfoMapper;
import com.runmi.webchat.aftersale.web.api.service.SetupService;
import com.runmi.webchat.aftersale.web.api.vo.SetupQueryOrderResItemVo;
import com.runmi.webchat.aftersale.web.api.vo.SetupQueryOrderResVo;
import com.runmi.webchat.aftersale.web.api.vo.SetupReqVo;
import com.runmi.webchat.aftersale.web.set.model.RoleIndex;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value = "/webchatapi/setup")
public class SetupController {
	
	protected static final Log log = LogFactory.getLog("logFile");
	
	@Autowired
	private SetupService setupService;
	
	@Autowired
	private SetupOrderDao setupOrderDao;
	
	@Autowired
	private SetupOrderMapper setupOrderMapper;
	
	@Autowired
	private SetupItemMapper setupItemMapper;
	
	@Autowired
	private RegionInfoMapper regionInfoMapper;
	
	@Autowired
	private UserOpenIdDao userOpenIdDao;
	
	@Autowired
	private SetupItemDao setupItemDao;
	
	@Autowired
	private ShopInfoMapper shopInfoMapper;
	
	
	
	
	@Autowired
	private SetupOrderDetailMapper setupOrderDetailMapper;
	
	@Autowired
	private SetupOrderDetailDao setupOrderDetailDao;
	
	@Autowired
	private SetupMail setupMail;
	
	
	@ApiOperation(value = "获取安装商品列表", notes = "获取安装商品列表",tags={ "微信API", })
	@RequestMapping(value = "/getItem",method = RequestMethod.GET)
	@ResponseBody
	public List<SetupItem> getItem(
			@ApiParam(value = "门店ID",required = true)@RequestParam(value = "shopId") Integer shopId){
		return setupService.getItem(shopId);   	
	}
	
	@ApiOperation(value = "保存安装请求", notes = "保存安装请求",tags={ "微信API", })
	@PostMapping(value = "/save")
	@ResponseBody
	public Result saveSetup(
			@ApiParam(value = "微信OPENID",required = true)@RequestParam(value = "openId") String openId,
			@ApiParam(value = "门店ID",required = true)@RequestParam(value = "shopId") Integer shopId,
			@ApiParam(value = "客户姓名",required = true)@RequestParam(value = "customerName") String customerName,
			@ApiParam(value = "手机",required = true)@RequestParam(value = "mobile") String mobile,
			@ApiParam(value = "省份ID",required = true)@RequestParam(value = "provinceId") Integer provinceId,
			@ApiParam(value = "市ID",required = true)@RequestParam(value = "cityId") Integer cityId,
			@ApiParam(value = "县ID",required = true)@RequestParam(value = "areaId") Integer areaId,
			@ApiParam(value = "详细地址",required = true)@RequestParam(value = "addressDesc") String addressDesc,
			@ApiParam(value = "商品ID(1,2,3)",required = true)@RequestParam(value = "itemIds") String itemIds,
			@ApiParam(value = "预计上门安装时间(yyyy/MM/dd HH:mm:ss)",required = false)@RequestParam(value = "expectDate") String expectDate
			) throws Exception {
		if(null==shopId){
			return ResultFactory.getResultFail("请扫码提交安装申请");
		}
		
		Date expect=null;
		if (StringUtils.isNotBlank(expectDate)) {
			expect = DateUtil.parse(expectDate, "yyyy/MM/dd HH:mm:ss");
			
		}		
		List<Integer> itemIdList=new ArrayList<Integer>();
		String[] strs=itemIds.split(",");
		for(String str:strs){
			Integer id=Integer.parseInt(str);
			if(!itemIdList.contains(id)){
				itemIdList.add(id);
				
				Integer num= setupOrderMapper.checkOrderItem(openId, id);
				if(null!=num && num>0){
					SetupItem itemModel= setupItemMapper.selectByPrimaryKey(id);
					return ResultFactory.getResultFail("商品"+ itemModel.getItemName()+"安装请求已经提交 ");
				}
				//setupOrderDetailDao.getSetupOrderDetailByOrderIdAndItemId(orderId, itemId)
//				List<SetupOrder>  items= setupOrderDao.getSetupOrderByStatus(openId, itemId,(byte)1);
//				if(null!=items && items.size()>0){
//					return ResultFactory.getResultFail("安装请求已经提交 ");
//				}
			}
		}
		if(itemIdList.isEmpty()){
			return ResultFactory.getResultFail("未选中安装商品 ");
		}
		
		String orderNo=StringUtil.generateRandId();				
		SetupOrder setupOrder=new SetupOrder();
		setupOrder.setOrderNo(orderNo);
		setupOrder.setAddress(addressDesc);
		setupOrder.setOpenId(openId);
		setupOrder.setAreaId(areaId);
		setupOrder.setCityId(cityId);
		setupOrder.setShopId(shopId);
		setupOrder.setProvinceId(provinceId);
		setupOrder.setOpenId(openId);
		setupOrder.setCreateTime(new Date());
		setupOrder.setStatus((byte)1);
		setupOrder.setDelFlag((byte)0);
		setupOrder.setCustomerName(customerName);
		setupOrder.setMobile(mobile);
		setupOrder.setExpectDate(expect);
		//setupOrder.setItemId(itemId);
		setupOrderMapper.insert(setupOrder);
		
		for(Integer itemId:itemIdList){
			SetupOrderDetail setupOrderDetail=new SetupOrderDetail();
			setupOrderDetail.setCreateTime(new Date());
			setupOrderDetail.setDelFlag((byte)0);
			setupOrderDetail.setItemId(itemId);
			setupOrderDetail.setOrderId(setupOrder.getId());
			setupOrderDetailMapper.insert(setupOrderDetail);
		}		
		return ResultFactory.getResultSuccess();
		
	}
	
	@ApiOperation(value = "获取店铺安装列表", notes = "保存安装请求",tags={ "微信API", })
	@PostMapping(value = "/queryOrders")
	@ResponseBody
	public Result queryOrders(
			@ApiParam(value = "店铺ID",required = true)@RequestParam(value = "shopId") Integer shopId,
			@ApiParam(value = "状态1:申请 2：审核通过 3：已安装 4：拒绝",required = true)@RequestParam(value = "status") Byte status,
			@ApiParam(value = "页码",required = true)@RequestParam(value = "pageIndex") Integer pageIndex,
			@ApiParam(value = "大小",required = true)@RequestParam(value = "pageSize") Integer pageSize
	){
		
		PageModel pageMode=new PageModel();
		pageMode.setCpage(pageIndex);
		pageMode.setPageSize(pageSize);
//		
//		UserOpenId userInfo= userOpenIdDao.getShopUserByOpenId(openId);
//		if(null==userInfo){
//			return ResultFactory.getResultFail("店员信息错误");
//		}
//		if(userInfo.getShopId()!=shopId){
//			return ResultFactory.getResultFail("店员权限错误");
//		}
		List<Byte> statusIds=new ArrayList<Byte>();
		PageHelper.startPage(pageMode.getCpage(), pageMode.getPageSize());
		statusIds.add(status);
//		if(status.equals((byte)2)){
//			statusIds.add((byte)3);
//		}
		
		List<SetupOrder> items= setupOrderMapper.queryOrder(shopId, statusIds);			
		List<SetupQueryOrderResVo> itemsResult=new ArrayList<SetupQueryOrderResVo>();
		PageInfo<SetupOrder> pageInfo = new PageInfo<>(items);
		for(SetupOrder order:items){
			SetupQueryOrderResVo item=new SetupQueryOrderResVo();
			item.setOrderId(order.getId());
			item.setCustomerName(order.getCustomerName());
			item.setMobile(order.getMobile());
			item.setAddress(order.getAddress());
			RegionInfo regionInfoPr =regionInfoMapper.selectByPrimaryKey(order.getProvinceId());
			if(null!=regionInfoPr){
				item.setProvinceName(regionInfoPr.getRegionName());
			}
			RegionInfo regionInfo =regionInfoMapper.selectByPrimaryKey(order.getCityId());
			if(null!=regionInfo){
				item.setCityName(regionInfo.getRegionName());
			}
			RegionInfo regionInfoArea =regionInfoMapper.selectByPrimaryKey(order.getAreaId());
			if(null!=regionInfoArea){
				item.setAreaName(regionInfoArea.getRegionName());
			}
			item.setStatus(order.getStatus());
			//  `status` tinyint(4) DEFAULT NULL COMMENT '1:申请 2：审核通过 3：已安装 4：拒绝',
			
			if(null!=order.getStatus() && order.getStatus()==(byte)1){
				item.setStatusName("申请安装中");
			}
			if(null!=order.getStatus() && order.getStatus()==(byte)2){
				item.setStatusName("待安装");
			}
			if(null!=order.getStatus() && order.getStatus()==(byte)3){
				item.setStatusName("已安装");
			}
			if(null!=order.getStatus() && order.getStatus()==(byte)4){
				item.setStatusName("拒绝");
			}
			item.setCreateTime(DateUtil.format(order.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
			item.setExpectDate(DateUtil.format(order.getExpectDate(), "yyyy-MM-dd"));
						
			List<SetupOrderDetail> orderDetail= setupOrderDetailDao.getSetupOrderDetailByOrderId(order.getId());
			List<SetupQueryOrderResItemVo> itemVos=new ArrayList<SetupQueryOrderResItemVo>();
			for(SetupOrderDetail item1:orderDetail){
				SetupItem setupItem= setupItemMapper.selectByPrimaryKey(item1.getItemId());
				if(null!=setupItem){
					SetupQueryOrderResItemVo itemV=new SetupQueryOrderResItemVo();
					itemV.setItemName(setupItem.getItemName());
					itemV.setItemUrl(setupItem.getItemUrl());
					itemV.setBarCode(setupItem.getBarCode());
					itemVos.add(itemV);
				}
			}
			item.setItems(itemVos);
			itemsResult.add(item);
		}
		return ResultFactory.getResultSuccess(itemsResult);

	}
	
	@ApiOperation(value = "审核安装", notes = "保存安装请求",tags={ "微信API", })
	@PostMapping(value = "/auditOrder")
	@ResponseBody
	public Result auditOrder(
			@ApiParam(value = "店铺姓名",required = true)@RequestParam(value = "realName") String realName,
			@ApiParam(value = "订单ID",required = true)@RequestParam(value = "orderId") Integer orderId,
			@ApiParam(value = "订单状态 1:申请中  2已安装 3：已安装  4：拒绝",required = true)@RequestParam(value = "status") Byte status
			) throws Exception {
		
		SetupOrder setupOrder=setupOrderMapper.selectByPrimaryKey(orderId);
		if(null==setupOrder){
			return ResultFactory.getResultFail("未查询到订单");
		}
		
		SetupOrder record=new SetupOrder();
		record.setId(orderId);
		if(status.equals((byte)1)){
			status=(byte)2;
		}
		record.setStatus(status);
		record.setAuditOpenId(realName);
		if(status==(byte)3){
			record.setSetupTime(new Date());
		}
		if(status.equals((byte)2)){
			//审核   `item_type` tinyint(4) DEFAULT NULL COMMENT '0:不管库存 1：管库存',
			SetupOrder order= setupOrderMapper.selectByPrimaryKey(orderId);
			ShopInfo shopInfo= shopInfoMapper.selectByPrimaryKey(order.getShopId());
			
			List<SetupOrderDetail> setupItems= setupOrderDetailDao.getSetupOrderDetailByOrderId(orderId);
			if(null!=setupItems && setupItems.size()>0){
			 CompletableFuture.runAsync(() -> {
				 setupMail.sendMailTo(setupOrder,setupItems,shopInfo);
		        });	
			}
		}
		setupOrderMapper.updateByPrimaryKeySelective(record);				
		return ResultFactory.getResultSuccess();
		
	}
	


}
